package com.twu.biblioteca;

import com.twu.biblioteca.actions.*;
import com.twu.biblioteca.exceptions.ArgumentError;
import com.twu.biblioteca.exceptions.BaseError;
import com.twu.biblioteca.helper.Scanner;
import com.twu.biblioteca.models.ExitManagerImpl;
import com.twu.biblioteca.persistences.Books;

import java.util.InputMismatchException;

public class BibliotecaApp {
    Actions actions;

    public BibliotecaApp(){
        printWelcomeMessage();
        actions = getActions();
    }

    protected Actions getActions(){
        Books books = Books.getRootInstance();

        Actions actionLists = new Actions();
        actionLists.add(new QuitAction(new ExitManagerImpl()));
        actionLists.add(new ListAvailableBooksAction(books));
        actionLists.add(new BorrowBookAction(books));
        actionLists.add(new ReturnBookAction(books));

        return actionLists;
    }

    public void run(){
        while (true) {
            runSingleAction();
        }
    }

    public void runSingleAction(){
        actions.print();
        try {
            Integer actionID = readInteger();
            BaseAction action = actions.getAction(actionID);
            action.run();
        } catch (BaseError baseError) {
            printBaseError(baseError);
        }
    }

    protected void printWelcomeMessage(){
        System.out.println("\n --------------------------");
        System.out.println(" - Welcome to Biblioteca! -");
        System.out.println(" --------------------------");
    }

    protected void printBaseError(BaseError baseError){
        System.out.println(baseError.getMessage());
    }

    protected Integer readInteger() throws ArgumentError {
        Scanner scanner = new Scanner();
        return scanner.readInteger();
    }

    public static void main(String[] args) {
        BibliotecaApp app = new BibliotecaApp();
        app.run();
    }
}
